<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\AppMchTableModel;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\utils\Helper;

class AppMchTableService extends BaseModelService
{
    public static function getModel(){
        return new AppMchTableModel;
    }

    public static function getAllByAVendor($vendor)
    {
        $appInfo = AppInfoTableService::getByFilter(['vendor' => $vendor]);
        if (empty($appInfo)) {
            throw new ApiException("app is not allow pay",ErrnoPlus::COMMON_ERROR);
        }
        $res = self::getAllByFilter(["aid" => $appInfo['id']]);
        $mids = Helper::arraySmartUnique(array_column($res,'mid'));
        if(count($mids) < 1){
            return null;
        }
        $merchantInfo = MerchantInfoTableService::getAll($mids);
        return $merchantInfo;
    }


    public static function setRelationByAppInfo($appInfo,$mids){
        $merchantInfo = MerchantInfoTableService::getAll($mids);
        if(count($merchantInfo) != count($mids)){
            throw new ApiException("merchant info is not exist",ErrnoPlus::COMMON_ERROR);
        }
        $aid = $appInfo['id'];
        $relation = self::getAllByFilter([
            'aid' => $aid,
        ]);
        $relationMerchantIds = array_column($relation,'mid');
        $delInfo = array_diff($relationMerchantIds,$mids);
        $addInfo = array_diff($mids,$relationMerchantIds);
        if(count($delInfo) > 0){
            self::delByFilter([
                'aid' => $aid,
                'mid' => ['in',$delInfo],
            ]);
        }
        if(count($addInfo) > 0){
            $items = [];
            $tn = time();
            foreach($addInfo as $mid){
                $items[] = [
                    'mid' => $mid,
                    'aid' => $aid,
                    'first_time' => $tn,
                    'modify_time' => $tn,
                ];
            }
            self::addBulk($items);
        }
    }
}
